//
//  PhotoCollectionViewCell.swift
//  MQAlbum
//
//  Created by 许博 on 2017/4/10.
//  Copyright © 2017年 mechat. All rights reserved.
//

import UIKit
import Photos
protocol PhotoCollectionViewCellDelegate: class {
    func eventSelectNumberChange(number: Int);
    
}
class PhotoCollectionViewCell: UICollectionViewCell {
	

    /// 图片
    lazy var thumbnail:UIImageView = UIImageView()
    /// 选择图片
    lazy var imageSelect:UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "picture_select")
        return imageView
    }()

    /// 选择按钮
     lazy var selectButton:UIButton = {
        let btn = UIButton()
        btn.setImage((UIImage(named: "picture_unselect")), for: .normal)
        btn.addTarget(self, action: #selector(eventImageSelect), for: .touchUpInside)
        return btn
    }()
    
	weak var delegate: MQPhotoCollectionViewController?
    weak var eventDelegate: PhotoCollectionViewCellDelegate?
	
	var representedAssetIdentifier: String?
	var model : PHAsset?
	
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK:- 初始化UI
    func setupUI(){
        contentView.addSubview(thumbnail)
        contentView.addSubview(imageSelect)
        contentView.addSubview(selectButton)
        self.thumbnail.contentMode = .scaleAspectFill
        self.thumbnail.clipsToBounds = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let size = bounds.width
        thumbnail.frame = CGRect(x: 0, y: 0, width: size, height: size)
        imageSelect.frame = CGRect(x: size-25, y: 0, width: 25, height: 25)
        selectButton.frame = CGRect(x: size-25, y: 0, width: 25, height: 25)
    }
    
	override func awakeFromNib() {
		super.awakeFromNib()

	}
    
    func updateSelected(select:Bool){
        self.selectButton.isSelected = select
        self.imageSelect.isHidden = !select
        
        if select {
            self.selectButton.setImage(nil, for: UIControlState.normal)
        } else {
            self.selectButton.setImage(UIImage(named: "picture_unselect"), for: UIControlState.normal)
        }
    }
	
    // MARK:- 选择
    @objc func eventImageSelect(sender: UIButton) {
		if sender.isSelected {
			sender.isSelected = false
			self.imageSelect.isHidden = true
			sender.setImage(UIImage(named: "picture_unselect"), for: UIControlState.normal)
			if delegate != nil {
				if let index = MQPhotoImage.instance.selectedImage.index(of: self.model!) {
					MQPhotoImage.instance.selectedImage.remove(at: index)
				}
                
                if self.eventDelegate != nil {
                    self.eventDelegate!.eventSelectNumberChange(number: MQPhotoImage.instance.selectedImage.count)
                }
			}
		} else {
			
			if delegate != nil {
				if MQPhotoImage.instance.selectedImage.count >= MQPhotoPickerController.imageMaxSelectedNum - MQPhotoPickerController.alreadySelectedImageNum {
					self.showSelectErrorDialog() ;
					return;
				} else {
					MQPhotoImage.instance.selectedImage.append(self.model!)
                    
                    if self.eventDelegate != nil {
                        self.eventDelegate!.eventSelectNumberChange(number: MQPhotoImage.instance.selectedImage.count)
                    }
				}
			}
			
			sender.isSelected = true
            self.imageSelect.isHidden = false
			sender.setImage(nil, for: UIControlState.normal)
			
		}
	}
	
	private func showSelectErrorDialog() {
		if self.delegate != nil {
            let less = MQPhotoPickerController.imageMaxSelectedNum - MQPhotoPickerController.alreadySelectedImageNum
            
            let range = MQPhotoPickerConfig.ErrorImageMaxSelect.range(of:"#")
            var error = MQPhotoPickerConfig.ErrorImageMaxSelect
            error.replaceSubrange(range!, with: String(less))
            
			let alert = UIAlertController.init(title: nil, message: error, preferredStyle: UIAlertControllerStyle.alert)
			let confirmAction = UIAlertAction(title: MQPhotoPickerConfig.ButtonConfirmTitle, style: .default, handler: nil)
			alert.addAction(confirmAction)
			self.delegate?.present(alert, animated: true, completion: nil)
		}
	}
}
